import { ImageData } from '@/types/image'
import { Dataset } from '@/types/dataset'
import { Task, TaskResult } from '@/types/task'

// 模拟数据生成器配置
export interface MockDataConfig {
    mode: 'default' | 'large' | 'error' | 'empty' | 'slow'
    datasetCount?: number
    imageCount?: number
    taskCount?: number
    includeErrors?: boolean
}

// 不同场景的预设配置
export const MOCK_SCENARIOS = {
    default: {
        mode: 'default' as const,
        datasetCount: 5,
        imageCount: 3,
        taskCount: 3,
        includeErrors: false
    },
    large: {
        mode: 'large' as const,
        datasetCount: 20,
        imageCount: 50,
        taskCount: 10,
        includeErrors: false
    },
    error: {
        mode: 'error' as const,
        datasetCount: 3,
        imageCount: 2,
        taskCount: 2,
        includeErrors: true
    },
    empty: {
        mode: 'empty' as const,
        datasetCount: 0,
        imageCount: 0,
        taskCount: 0,
        includeErrors: false
    },
    slow: {
        mode: 'slow' as const,
        datasetCount: 5,
        imageCount: 3,
        taskCount: 3,
        includeErrors: false
    }
}

// 增强的模拟影像数据生成器
export const generateEnhancedImageData = (
    id: string,
    type: '2D' | '3D' = '3D',
    config: MockDataConfig = MOCK_SCENARIOS.default
): ImageData => {
    const baseData = {
        id,
        type,
        format: 'DICOM' as const,
        url: `/mock/images/${id}/data`,
        thumbnailUrl: `/mock/images/${id}/thumbnail`,
        createdAt: new Date(),
        updatedAt: new Date()
    }

    // 根据模式生成不同的数据
    switch (config.mode) {
        case 'large':
            return {
                ...baseData,
                dimensions: type === '3D'
                    ? { width: 1024, height: 1024, depth: 500 }
                    : { width: 2048, height: 2048 },
                pixelSpacing: [0.5, 0.5, 0.5],
                imageOrientation: [1, 0, 0, 0, 1, 0],
                imagePosition: [0, 0, 0],
                windowCenter: 400,
                windowWidth: 1600,
                pixelData: new ArrayBuffer(1024 * 1024 * (type === '3D' ? 500 : 1) * 2),
                metadata: {
                    patientName: `大数据集患者_${id}`,
                    patientId: `P${id.padStart(8, '0')}`,
                    studyDate: '2024-01-01',
                    studyTime: '120000',
                    modality: type === '3D' ? 'CT' : 'CR',
                    bodyPart: 'WHOLE_BODY',
                    manufacturer: 'Advanced Medical Systems',
                    studyDescription: '高分辨率全身扫描',
                    seriesDescription: '增强扫描序列',
                    sliceThickness: 0.5,
                    kvp: 120,
                    exposureTime: 1000,
                    xRayTubeCurrent: 200
                }
            }

        case 'error':
            // 模拟损坏或有问题的数据
            return {
                ...baseData,
                dimensions: { width: 0, height: 0, depth: 0 }, // 无效尺寸
                pixelSpacing: [0, 0, 0], // 无效像素间距
                windowCenter: NaN,
                windowWidth: NaN,
                pixelData: new ArrayBuffer(0), // 空数据
                metadata: {
                    patientName: '数据损坏',
                    patientId: 'ERROR',
                    studyDate: 'INVALID',
                    error: 'Corrupted DICOM file'
                }
            }

        case 'empty':
            return {
                ...baseData,
                dimensions: { width: 1, height: 1 },
                pixelSpacing: [1, 1, 1],
                windowCenter: 0,
                windowWidth: 1,
                pixelData: new ArrayBuffer(1),
                metadata: {
                    patientName: '空数据集',
                    patientId: 'EMPTY'
                }
            }

        default:
            return {
                ...baseData,
                dimensions: type === '3D'
                    ? { width: 512, height: 512, depth: 100 }
                    : { width: 1024, height: 1024 },
                pixelSpacing: [1.0, 1.0, 1.0],
                imageOrientation: [1, 0, 0, 0, 1, 0],
                imagePosition: [0, 0, 0],
                windowCenter: 400,
                windowWidth: 1600,
                pixelData: new ArrayBuffer(512 * 512 * (type === '3D' ? 100 : 1) * 2),
                metadata: {
                    patientName: `测试患者_${id}`,
                    patientId: `P${id.padStart(6, '0')}`,
                    studyDate: '2024-01-01',
                    studyTime: '120000',
                    modality: type === '3D' ? 'CT' : 'CR',
                    bodyPart: 'CHEST',
                    manufacturer: 'Mock Medical Systems',
                    studyDescription: '常规检查',
                    seriesDescription: '标准序列'
                }
            }
    }
}

// 增强的模拟任务生成器
export const generateEnhancedTasks = (
    datasetId: string,
    config: MockDataConfig = MOCK_SCENARIOS.default
): Task[] => {
    const taskTypes = [
        {
            type: 'detection' as const,
            name: '病灶检测',
            description: '自动检测影像中的异常病灶区域'
        },
        {
            type: 'classification' as const,
            name: '影像分类',
            description: '对影像进行疾病分类诊断'
        },
        {
            type: 'segmentation' as const,
            name: '器官分割',
            description: '分割影像中的器官和组织结构'
        }
    ]

    const tasks: Task[] = []
    const taskCount = Math.min(config.taskCount || 3, taskTypes.length)

    for (let i = 0; i < taskCount; i++) {
        const taskType = taskTypes[i]
        const taskId = `task_${datasetId}_${i + 1}`

        let status: Task['status'] = 'idle'
        let taskConfig: any = {
            parameters: {},
            modelEndpoint: `/models/${taskType.type}`
        }

        // 根据模式设置不同的任务状态和配置
        switch (config.mode) {
            case 'large':
                taskConfig.parameters = {
                    batchSize: 32,
                    epochs: 100,
                    learningRate: 0.001,
                    augmentation: true,
                    modelComplexity: 'high'
                }
                status = i === 0 ? 'running' : 'idle'
                break

            case 'error':
                taskConfig.parameters = {
                    invalidParam: 'error_value'
                }
                status = 'error'
                break

            case 'empty':
                taskConfig.parameters = {}
                status = 'idle'
                break

            default:
                taskConfig.parameters = {
                    threshold: 0.5,
                    maxDetections: 10
                }
                status = i === 0 ? 'completed' : 'idle'
        }

        tasks.push({
            id: taskId,
            name: taskType.name,
            type: taskType.type,
            description: taskType.description,
            config: taskConfig,
            status,
            datasetId,
            priority: i + 1,
            createdAt: new Date(Date.now() - (i * 24 * 60 * 60 * 1000)), // 递减日期
            updatedAt: new Date()
        })
    }

    return tasks
}

// 增强的模拟数据集生成器
export const generateEnhancedDataset = (
    id: string,
    type: '2D' | '3D' = '3D',
    config: MockDataConfig = MOCK_SCENARIOS.default
): Dataset => {
    const datasetNames = {
        '3D': ['胸部CT', '脑部MRI', '腹部CT', '脊柱MRI', '心脏CT'],
        '2D': ['胸部X光', '乳腺钼靶', '骨骼X光', '牙科全景', '眼底照片']
    }

    const descriptions = {
        '3D': [
            '高分辨率三维CT影像数据集，用于肺部疾病检测和分析',
            '多序列脑部MRI数据集，支持神经疾病诊断',
            '腹部多期增强CT数据集，用于器官分割和病灶检测',
            '脊柱MRI数据集，用于椎间盘和脊髓病变分析',
            '心脏CT血管造影数据集，用于冠心病筛查'
        ],
        '2D': [
            '胸部X光影像数据集，用于肺炎和结核病筛查',
            '乳腺钼靶X光数据集，用于乳腺癌早期筛查',
            '骨骼X光数据集，用于骨折和骨病诊断',
            '口腔全景X光数据集，用于牙科疾病诊断',
            '眼底彩色照片数据集，用于糖尿病视网膜病变筛查'
        ]
    }

    const nameIndex = parseInt(id) % datasetNames[type].length
    const name = datasetNames[type][nameIndex] || `${type}数据集_${id}`
    const description = descriptions[type][nameIndex] || `${type}影像数据集`

    // 生成影像数据
    const images: ImageData[] = []
    const imageCount = config.imageCount || 3

    if (config.mode !== 'empty') {
        for (let i = 0; i < imageCount; i++) {
            images.push(generateEnhancedImageData(`${id}_img_${i + 1}`, type, config))
        }
    }

    // 生成任务
    const tasks = config.mode !== 'empty'
        ? generateEnhancedTasks(id, config)
        : []

    // 计算数据集大小
    let size = 0
    switch (config.mode) {
        case 'large':
            size = 1024 * 1024 * 1024 * 5 // 5GB
            break
        case 'empty':
            size = 0
            break
        default:
            size = 1024 * 1024 * 100 // 100MB
    }

    return {
        id,
        name,
        description,
        type,
        tasks,
        images,
        imageCount: images.length,
        size,
        tags: generateTags(type, config.mode),
        isPublic: true,
        owner: config.mode === 'error' ? 'unknown' : 'test_user',
        createdAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000), // 随机过去30天内
        updatedAt: new Date()
    }
}

// 生成标签
const generateTags = (type: '2D' | '3D', mode: string): string[] => {
    const baseTags = type === '3D'
        ? ['3D', 'CT', 'MRI', '医学影像']
        : ['2D', 'X光', '平片', '医学影像']

    const modeTags: Record<string, string[]> = {
        large: ['大数据集', '高分辨率'],
        error: ['测试', '错误场景'],
        empty: ['空数据'],
        slow: ['性能测试'],
        default: ['标准', '测试']
    }

    return [...baseTags, ...(modeTags[mode] || [])]
}

// 生成模拟任务结果
export const generateMockTaskResult = (
    taskId: string,
    taskType: Task['type'],
    config: MockDataConfig = MOCK_SCENARIOS.default
): TaskResult => {
    const baseResult = {
        id: `result_${taskId}_${Date.now()}`,
        taskId,
        executionTime: config.mode === 'slow' ? 5000 : 120,
        createdAt: new Date()
    }

    if (config.mode === 'error') {
        return {
            ...baseResult,
            status: 'error' as const,
            error: 'Task execution failed: Mock error scenario',
            data: undefined
        }
    }

    // 根据任务类型生成不同的结果数据
    switch (taskType) {
        case 'detection':
            return {
                ...baseResult,
                status: 'success' as const,
                data: {
                    detections: config.mode === 'large'
                        ? Array.from({ length: 50 }, (_, i) => ({
                            id: `det_${i + 1}`,
                            bbox: [
                                Math.random() * 400,
                                Math.random() * 400,
                                50 + Math.random() * 100,
                                50 + Math.random() * 100
                            ],
                            confidence: 0.5 + Math.random() * 0.5,
                            class: ['nodule', 'mass', 'opacity'][Math.floor(Math.random() * 3)],
                            slice: Math.floor(Math.random() * 100)
                        }))
                        : [
                            {
                                id: 'det_1',
                                bbox: [100, 100, 50, 50],
                                confidence: 0.85,
                                class: 'nodule',
                                slice: 45
                            },
                            {
                                id: 'det_2',
                                bbox: [200, 150, 30, 40],
                                confidence: 0.72,
                                class: 'mass',
                                slice: 52
                            }
                        ]
                },
                metrics: {
                    accuracy: 0.92,
                    precision: 0.88,
                    recall: 0.90,
                    f1Score: 0.89,
                    totalDetections: config.mode === 'large' ? 50 : 2
                }
            }

        case 'classification':
            return {
                ...baseResult,
                status: 'success' as const,
                data: {
                    predictions: [
                        { class: 'normal', confidence: 0.15 },
                        { class: 'abnormal', confidence: 0.85 }
                    ],
                    finalPrediction: 'abnormal'
                },
                metrics: {
                    accuracy: 0.94,
                    precision: 0.91,
                    recall: 0.93,
                    f1Score: 0.92
                }
            }

        case 'segmentation':
            return {
                ...baseResult,
                status: 'success' as const,
                data: {
                    segmentationMask: `/mock/results/${taskId}/mask.nii`,
                    segments: [
                        { id: 'lung_left', volume: 2500, confidence: 0.95 },
                        { id: 'lung_right', volume: 2600, confidence: 0.93 },
                        { id: 'heart', volume: 800, confidence: 0.89 }
                    ]
                },
                metrics: {
                    diceScore: 0.87,
                    jaccardIndex: 0.78,
                    hausdorffDistance: 2.3
                }
            }

        default:
            return {
                ...baseResult,
                status: 'success' as const,
                data: { message: 'Task completed successfully' }
            }
    }
}

// 主要的增强模拟数据生成器
export class EnhancedMockDataGenerator {
    private config: MockDataConfig

    constructor(config: MockDataConfig = MOCK_SCENARIOS.default) {
        this.config = config
    }

    // 更新配置
    updateConfig(config: Partial<MockDataConfig>) {
        this.config = { ...this.config, ...config }
    }

    // 生成数据集列表
    generateDatasets(): Dataset[] {
        if (this.config.mode === 'empty') {
            return []
        }

        const datasets: Dataset[] = []
        const count = this.config.datasetCount || 5

        for (let i = 1; i <= count; i++) {
            const type: '2D' | '3D' = i % 2 === 0 ? '2D' : '3D'
            datasets.push(generateEnhancedDataset(i.toString(), type, this.config))
        }

        return datasets
    }

    // 生成单个数据集
    generateDataset(id: string, type?: '2D' | '3D'): Dataset {
        const datasetType = type || (parseInt(id) % 2 === 0 ? '2D' : '3D')
        return generateEnhancedDataset(id, datasetType, this.config)
    }

    // 生成影像数据
    generateImageData(id: string, type?: '2D' | '3D'): ImageData {
        const imageType = type || '3D'
        return generateEnhancedImageData(id, imageType, this.config)
    }

    // 生成任务结果
    generateTaskResult(taskId: string, taskType: Task['type']): TaskResult {
        return generateMockTaskResult(taskId, taskType, this.config)
    }

    // 获取当前配置
    getConfig(): MockDataConfig {
        return { ...this.config }
    }
}

// 导出默认实例
export const mockDataGenerator = new EnhancedMockDataGenerator()

export default EnhancedMockDataGenerator